//
//  AppDelegate.m
//  QKWeibo-OC
//
//  Created by iMac_Kurt on 16/8/11.
//  Copyright © 2016年 Kurt_Qi. All rights reserved.
//

#import "AppDelegate.h"
#import "QKMainTabBarController.h"
#import "QKUserAccountViewModel.h"
#import "QKNewFeatureCollectionViewController.h"
#import "QKWelcomeViewController.h"

@interface AppDelegate ()

@property (nonatomic, assign, getter=isNewVersion) BOOL version;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //
    [self setupAppearance];
    
    // 测试：解档用户账户数据
//    QKUserAccountViewModel *viewModel = [QKUserAccountViewModel sharedUserAccount];
//    NSLog(@"%@", viewModel.account);
    
    //
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    self.window.rootViewController = [self defaultRootViewController];
    
    [self.window makeKeyAndVisible];
    
    // 监听通知
    [[NSNotificationCenter defaultCenter] addObserverForName:QKSwitchRootViewControllerNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        
        // 判断是否为新版本
        if (self.isNewVersion) {
            self.window.rootViewController = [[QKNewFeatureCollectionViewController alloc] init];
        }else if (note.object != nil) {
            // 判断object是否为nil来控制切换到不同控制器
            // 如果object有值，切换到欢迎界面
            self.window.rootViewController = [[QKWelcomeViewController alloc] init];
        }else {
            self.window.rootViewController = [[QKMainTabBarController alloc] init];
        }
        
    }];
    
    return YES;
}
// 注销通知
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:QKSwitchRootViewControllerNotification object:nil];
}

// 全局外观
- (void)setupAppearance {
    [UINavigationBar appearance].tintColor = QKWBAppearanceTintColor;
    [UITabBar appearance].tintColor = QKWBAppearanceTintColor;
}

// 默认根控制器
- (UIViewController *)defaultRootViewController {
    // 先判断用户登录情况
    if ([QKUserAccountViewModel sharedUserAccount].userLogon) {
        return self.isNewVersion ? [[QKNewFeatureCollectionViewController alloc] init] : [[QKWelcomeViewController alloc] init];
    }
    return [[QKMainTabBarController alloc] init];
}
// 是否为新版本
- (BOOL)isNewVersion {
    // 获取当前版本
    //NSLog(@"%@", [NSBundle mainBundle].infoDictionary);
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    double version = currentVersion.doubleValue;
    
    // 判断是否有新版本
    // 从沙盒中取出之前的版本
    NSString *sandboxVersionKey = @"sandboxVersionKey";
    double sandboxVersion = [[NSUserDefaults standardUserDefaults] doubleForKey:sandboxVersionKey];
    
    // 将当前版本储存到用户偏好设置
    [[NSUserDefaults standardUserDefaults] setDouble:version forKey:sandboxVersionKey];
    
    return version > sandboxVersion;
}

@end
